package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.HttpConfig;
import org.apache.commons.fileupload.FileUploadException;

import dao.FileUploadDAO;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class FileUpload
 */
public class RegisterAlgorithm extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static String result = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterAlgorithm() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("userId");
		// 得到文件上传目录，将上传的文件保存至WEB-INF目录下，不允许外界访问，保证上传文件的安全
		String savePath = HttpConfig.algorithmFileUri;
//		FileUploadDAO f = new FileUploadDAO(request, response, 150 * 1024 * 1024, savePath);
		FileUploadDAO f = new FileUploadDAO(request, response, HttpConfig.maxUploadSize, savePath);
		boolean isSuccess = false;
		JSONObject result = new JSONObject();
		try {
			isSuccess = f.executeUpload(userId);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		result.put("message", RegisterAlgorithm.result);
		result.put("result", isSuccess);
		response.getWriter().write(result.toString());
		RegisterAlgorithm.result = "";
	}

}
